<?php

namespace App\Jobs;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Redis;


class ApplyOrderPayingJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected User $user;

    protected array $unpaidCacheIds = [];

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(User $user, $unpaidCacheIds)
    {
        $this->user = $user;
        $this->unpaidCacheIds = $unpaidCacheIds;
    }

    /**
     * Execute the job.

     *
     * @return void
     */
     public function handle()
    {
        $key = "{$this->user->id}_order_list";

        $topId = Redis::get($key);

         if(!$topId){
            Redis::set($key,0);
        }
        Redis::incr($key);
        $uniqueId = Redis::get($key);
        $user = $this->user;
        $orderKey  = $user::sUnpaidOrderListCacheKey($user->id,$uniqueId);

        foreach($this->unpaidCacheIds as $cacheId){

             Redis::zAdd($orderKey , 1, $cacheId);
        }
        cashier('balance')->payCacheOrder($orderKey);
        
    }
}
